/**
 * Yolema.com Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */
package org.grayrabbit.pay.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.grayrabbit.pay.chinapnr.common.PnrConstants;
import org.grayrabbit.pay.chinapnr.config.ChinapnrConfigUtil;
import org.grayrabbit.pay.chinapnr.config.ChinapnrInfo;
import org.grayrabbit.pay.chinapnr.params.ChinapnrFormParams;
import org.grayrabbit.pay.chinapnr.params.ChinapnrPayForm;
import org.grayrabbit.pay.chinapnr.params.ChinapnrRefundForm;
import org.grayrabbit.pay.core.model.exception.PayException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 汇付支付
 * 
 * @author wy
 * @version $Id: ChinapnrPay.java, v 0.1 2012-11-4 下午5:54:43 wy Exp $
 */
public class ChinapnrPay {

    private final static Logger LOG = LoggerFactory.getLogger(ChinapnrPay.class);

    /**
     * 退款
     * 
     * @param form
     * @return 
     * @see PnrConstants#TRADE_REQUEST_MAP
     */
    public LinkedHashMap<String, String> refund(ChinapnrRefundForm form) {
        //检查数据
        form.check();
      //检查数据
        form.check();

        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

        map.put(ChinapnrFormParams.SEND_REFUND_VERSION, PnrConstants.TRADE_VERSION);
        map.put(ChinapnrFormParams.SEND_REFUND_CMDID, PnrConstants.TRADE_TELREFUND);
        map.put(ChinapnrFormParams.SEND_REFUND_MERID, ChinapnrConfigUtil.getChinapnrInfo()
            .getMemId());
        String orderId = form.getTradeId();
        map.put(ChinapnrFormParams.SEND_REFUND_ORDID, orderId);
        map.put(ChinapnrFormParams.SEND_REFUND_OLD_ORDID, form.getOldTradeId());
        map.put(ChinapnrFormParams.SEND_SEND_REFUND_REFAMT, form.getMoney());

        map.put(ChinapnrFormParams.SEND_SEND_REFUND_BGRETURL, "");
        map.put(ChinapnrFormParams.SEND_SEND_REFUND_DIVDETAILS, "");
        map.put(ChinapnrFormParams.SEND_SEND_REFUND_CHKVALUE, form.getChkValue());

        String url = ChinapnrConfigUtil.getChinapnrInfo().getTradeUrl();

        HttpResponse response = HttpUtil.httpPost(url, map);

        HttpEntity entity = response.getEntity();

        LOG.info("返回HTTP状态{}", response.getStatusLine().getStatusCode());

        if (entity == null) {
            throw new PayException("交易返回结果为空");
        }
        LinkedHashMap<String, String> responseMap = new LinkedHashMap<String, String>();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(),
                "GBK"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (StringUtils.isBlank(line)) {
                    continue;
                } else if (line.indexOf("=") == -1) {
                    LOG.info("返回参数{}错误没‘=’号", line);
                }
                String[] param = line.split("=");
                responseMap.put(param[0], param[1]);
            }
        } catch (UnsupportedEncodingException e) {
            LOG.error("不支持的返回结果转码", e);
            throw new PayException("不支持的返回结果转码");
        } catch (IllegalStateException e) {
            LOG.error("返回结果IllegalStateException", e);
            throw new PayException("返回结果IllegalStateException");
        } catch (IOException e) {
            LOG.error("返回结果IOException", e);
            throw new PayException("返回结果IOException");
        }

        return responseMap;
    }

    /**
     * 收款
     * 
     * @param form
     * @param baseUrl
     * @return
     * @see PnrConstants#TRADE_REQUEST_MAP
     */
    public LinkedHashMap<String, String> pay(ChinapnrPayForm form, String baseUrl) {

        //检查数据
        form.check();

        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

        map.put(ChinapnrFormParams.SEND_TRADE_VERSION, PnrConstants.TRADE_VERSION);
        map.put(ChinapnrFormParams.SEND_TRADE_CMDID, PnrConstants.TRADE_TELPAY);
        map.put(ChinapnrFormParams.SEND_TRADE_MERID, ChinapnrConfigUtil.getChinapnrInfo()
            .getMemId());
        String orderId = form.getTradeId();
        map.put(ChinapnrFormParams.SEND_TRADE_ORDID, orderId);
        map.put(ChinapnrFormParams.SEND_TRADE_ORDAMT, String.valueOf(form.getMoney()));

        map.put(ChinapnrFormParams.SEND_TRADE_GATEID, form.getGate().getGate());
        //用户私有域
        map.put(ChinapnrFormParams.SEND_TRADE_MERPRIV, form.getMerPriv());
        map.put(ChinapnrFormParams.SEND_TRADE_DIVDETAILS, "");
        map.put(ChinapnrFormParams.SEND_TRADE_BGRETURL, baseUrl
                                                        + ChinapnrInfo.TRADE_BACKGROUND_RESULT_URL);

        map.put(ChinapnrFormParams.SEND_TRADE_CARDINFO, form.getCardInfo());
        map.put(ChinapnrFormParams.SEND_TRADE_CHKVALUE, form.getChkValue(baseUrl));

        String url = ChinapnrConfigUtil.getChinapnrInfo().getTradeUrl();

        HttpResponse response = HttpUtil.httpPost(url, map);

        HttpEntity entity = response.getEntity();

        LOG.info("返回HTTP状态{}", response.getStatusLine().getStatusCode());

        if (entity == null) {
            throw new PayException("交易返回结果为空");
        }
        LinkedHashMap<String, String> responseMap = new LinkedHashMap<String, String>();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(),
                "GBK"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (StringUtils.isBlank(line)) {
                    continue;
                } else if (line.indexOf("=") == -1) {
                    LOG.info("返回参数{}错误没‘=’号", line);
                }
                String[] param = line.split("=");
                responseMap.put(param[0], param[1]);
            }
        } catch (UnsupportedEncodingException e) {
            LOG.error("不支持的返回结果转码", e);
            throw new PayException("不支持的返回结果转码");
        } catch (IllegalStateException e) {
            LOG.error("返回结果IllegalStateException", e);
            throw new PayException("返回结果IllegalStateException");
        } catch (IOException e) {
            LOG.error("返回结果IOException", e);
            throw new PayException("返回结果IOException");
        }

        return responseMap;
    }
}
